<script setup>

import {ElTable, ElMessage, ElMessageBox} from 'element-plus';
import axios, {head} from "axios";
import {nextTick, onMounted, reactive, ref} from 'vue';
import {Refresh, Search} from "@element-plus/icons-vue";
import {ElLoading} from 'element-plus'
import router from "@/router";
import TextEditor from "@/util/TextEditor.vue";
let content = '';

let tableData = ref([])


//修改全部字段
let dialogFormVisible = ref(false)
const xiugaitanchukuang = (row) => {
  form.value = {...row}; // 将行数据复制到表单中
  dialogFormVisible.value = true; // 显示对话框
};


dialogFormVisible.value = false;
const FormVisible = ref(false);
const fromLabelWidth = '140px';
const form = ref({
  articleId: '',
  title: '',
  content: '',
  publishTime: '',
  imageUrl: '',
  consultantId: '',

})
//分页查询


const formData = ref({
  pageNum: 1,// 页码
  pageSize: 5, // 每页展示条
})


//查询全部
// const testGet = () => {
//   console.log("Get.....")
//   axios.get("/featuredarticle")
//       .then(resp => {
//         console.log(resp.data);
//         tableData.value = resp.data.data;
//         nextTick(() => {
//           console.log(tableData.value)
//         });
//       })
//       .catch(err => {
//         console.log(err);
//       })
// }


//分页查询
const testGet = ()=>{
  console.log("Get......")
  let params = {
    start: formData.value.pageNum,
    pageSize: formData.value.pageSize,
  };
  axios.get("/featuredarticle/findbypage", {params:params})
      .then(resp =>{
        console.log(resp.data);
        tableData.value = resp.data.data.list;
      })
      .catch(err => {
        console.log(err);
      })
}

function handleFileChanges(value){
  console.log("111",value)
}

// 分页查询
// function pageNumChange(num) {
//   // 修改页码
//   formData.value.pageNum = num;
//   // 再次进行查询
//   getAll();
// }




//修改
const testPut = () => {
  console.log("Put.....")
  axios.put("/featuredarticle", {
    articleId: form.value.articleId,
    title: form.value.title,
    content: form.value.content,
    imageUrl: form.value.imageUrl,
    consultantId: form.value.consultantId

  }, {
    headers: {"Content-Type": "multipart/form-data"}
  })
      .then(resp => {
        console.log(resp);
        testGet();
        console.log("-------------------");
      })
      .catch(err => {
        console.log(err);
      })
  dialogFormVisible.value = false
}

//删除
const testDelete = (row) => {
  console.log("Delete.....")
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete("/featuredarticle", {
      params: {articleId: row.articleId}
    })
        .then(resp => {
          console.log(resp);
          testGet();
        })
        .catch(err => {
          console.log(err);
        })
  }).catch(() => {
    console.log('取消删除');
  })
}

// 存储用户选择的文件
const selectedFile = ref(null);
// 存储上传成功后的 URL
const uploadedUrl = ref('');

// 存储错误信息
const errorMessage = ref('');



// 选着文件
const handleFileChange=async (event)=>{
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型是否为 JPEG 或 PNG
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    // 检查文件大小是否小于 2MB
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJpgOrPng) {
      errorMessage.value = '上传图片只能是 JPG 或 PNG 格式';
      return;
    }
    if (!isLt2M) {
      errorMessage.value = '上传文件大小不能超过 2MB';
      return;
    }
    selectedFile.value = file;
  } else {
    selectedFile.value = null;
  }
  console.log(selectedFile.value);
  event.preventDefault();
  if (!selectedFile.value) {
    errorMessage.value = '请先选择要上传的文件';
    return;
  }
  const formData = new FormData();
  formData.append('file', selectedFile.value);
  try {
    // 发送文件上传请求，将 http://你的后端服务器地址/upload 替换为实际的后端服务地址
    const response = await axios.post('/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    uploadedUrl.value = response.data;
    form.value.imageUrl=response.data;
    errorMessage.value = '';
    console.log('文件上传成功，返回的 URL：', response.data);
  }

  catch (error) {
    errorMessage.value = '文件上传失败，错误信息：' + error.message;
    console.error('文件上传失败，错误信息：', error);
  }

}


//添加
const testPost = () => {
  console.log("post.....")
  axios.post("/featuredarticle", form.value)
      .then(resp => {
        console.log(resp);
        testGet();
      })
      .catch(err => {
        console.log(err);
      })
  FormVisible.value = false;
}



// 刷新
const shuaxin = () => {
  testGet();
}
//重置按钮
const openFullScreen2 = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  setTimeout(() => {
    loading.close()
  }, 500)
  shuaxin();
}

//搜索
let articlebianhao = ref();
const search = () => {
  if (articlebianhao.value === 0) {
    ElMessage.warning('请输入文章编号');
    return;
  }
  axios.get('/featuredarticle/findbyid', {
    params: {
      articleId: articlebianhao.value
    }
  })
      .then(resp => {
        console.log(resp.data.data);
        tableData.value = []
        tableData.value.push(resp.data.data);
      })
      .catch(err => {
        console.log(err);
        // alert("err");
      })


}

function handleSizeChange(val) {
  console.log('##############',val)
}
function handleCurrentChange(val) {
  formData.value.pageNum = val;
  testGet();
}
function currentPage1(val) {
  console.log('##############33366ss',val)
}
//跳转到收藏页面
onMounted(testGet);
const coursecollect = () => {
  router.push({
    path: '/home/shoucang',
  })
}
</script>
<template>
  <div>
    精选文章
    <div class="top">

      文章编号
      <el-input v-model="articlebianhao" style="width: 240px" placeholder="请输入文章id"/>
      文章标题
<!--      <el-input v-model="articletitle" style="width: 240px" placeholder="请输入文章标题"/>-->
      <el-button type="primary" style="margin-left: 20px" @click="search" :icon="Search">搜索</el-button>
      <el-button type="warning" style="margin-left: 20px" @click="shuaxin" :icon="Refresh">重置</el-button>
    </div>

    <div class="title">
      <el-button type="primary" @click="FormVisible = true">添加文章</el-button>
    </div>
    <el-button class="shuaxin" type="primary" @click="openFullScreen2">点击刷新</el-button>
    <el-button class="shuaxin" type="primary" @click="coursecollect">课程收藏</el-button>
    <div>

      <!--      显示全部-->
      <el-table :data="tableData" script style="width:1200px">
        <!--        <el-table-column type="selection" width="55" />-->
        <el-table-column prop="articleId" label="文章编号" width="90"/>
        <el-table-column prop="title" label="文章标题" width="120"/>
        <el-table-column prop="content" label="内容" width="300"/>
        <el-table-column prop="publishTime" label="发布时间" width="260"/>
        <el-table-column property="" label="课程图片" width="160">
          <template #default="scope">
            <img :src="scope.row.imageUrl" alt="头像" style="width: 120px; height: 80px;">
          </template>
        </el-table-column>
        <el-table-column prop="consultantId" label="咨询师编号" width="120"/>
        <el-table-column prop="scope" label="操作" width="180">
          <!--          插槽:修改和删除按钮-->
          <template #default="scope">
            <!--            <el-button type="primary" size="small" @click="dialogFormVisible = true">修改</el-button>-->
            <el-button type="primary" size="small" @click="xiugaitanchukuang(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="testDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--      分页-->
      <div class="example-pagination-block">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage1"
            :page-size="100"
            layout=" pager, next"
            :total="1000">
        </el-pagination>
      </div>

    </div>
  </div>


  <!--  修改全部字段-->
  <el-dialog v-model="dialogFormVisible" title="修改文章" width="700">
    <el-form :model="form">
      <el-form-item label="文章编号" :label-width="fromLabelWidth">
        <el-input v-model="form.articleId" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="文章标题" :label-width="fromLabelWidth">
        <el-input v-model="form.title" autocomplete="off"/>
      </el-form-item>
      <TextEditor v-model="form.content"></TextEditor>
      <el-form-item label="内容" :label-width="fromLabelWidth">
        <el-input
            type="textarea"
            v-model="form.content"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="发布时间" :label-width="fromLabelWidth">
        <el-input v-model="form.publishTime" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="课程图片" :label-width="fromLabelWidth">
        <input type="file" id="imageUrl">
      </el-form-item>
      <el-form-item label="咨询师编号" :label-width="fromLabelWidth">
        <el-input v-model="form.consultantId" autocomplete="off"/>
      </el-form-item>
      <!--  确认对话框-->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="testPut">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!--    添加文章-->
  <el-dialog v-model="FormVisible" title="添加文章" width="700">
    <el-form :model="form">
      <el-form-item label=" 文章编号" :label-width="fromLabelWidth">
        <el-input autocomplete="off" placeholder="id自动生成"/>
      </el-form-item>
      <el-form-item label=" 文章标题" :label-width="fromLabelWidth">
        <el-input v-model="form.title" autocomplete="off"/>
      </el-form-item>
      <TextEditor v-model="form.content"></TextEditor>
      <el-form-item label="内容" :label-width="fromLabelWidth">
        <el-input
            type="textarea"
            v-model="form.content"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="发布时间" :label-width="fromLabelWidth">
        <el-input v-model="form.publishTime" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="上传图片" :label-width="fromLabelWidth">
        <input type="file" id="fileInput" @change="handleFileChange" />
        <!--          <button id="uploadButton" @click="shangchuang">上传文件</button>-->

        <div v-if="uploadedUrl">上传成功，URL: {{ uploadedUrl }}</div>
        <div v-if="errorMessage" style="color: red">{{ errorMessage }}</div>
      </el-form-item>
      <el-form-item label=" 咨询师编号" :label-width="fromLabelWidth">
        <el-input v-model="form.consultantId" autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="FormVisible = false">取消</el-button>
        <el-button type="primary" @click="testPost()">确认</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<style scoped>
.title {
  display: inline-block;
  margin-right: 30px;
}
.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
</style>